//
//  SSWBNewFeatureView.swift
//  shanshanlol微博
//
//  Created by 叶竞泽 on 2017/1/21.
//  Copyright © 2017年 JingZe. All rights reserved.
//

import UIKit

class SSWBNewFeatureView: UIView {
    
    class func newFeatureView() -> SSWBNewFeatureView? {
        
        let nib = UINib.init(nibName: "SSWBNewFeatureView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as? SSWBNewFeatureView
        
        // 从xib加载的视图,默认是600*600,需要手动指定大小
        v?.frame = UIScreen.main.bounds
        
        return v
    }

    /// 滚动视图
    @IBOutlet weak var scrollView: UIScrollView!
    
    /// 开始按钮
    @IBOutlet weak var startButton: UIButton!
    
    /// 页面控制器
    @IBOutlet weak var pageControl: UIPageControl!
    
    /// 进入微博的方法
    @IBAction func enterStatus(_ sender: UIButton) {
        
        removeFromSuperview()
    }
    
    override func awakeFromNib() {
        
        // 使用自动布局设置的界面从xib加载,默认为600*600
        
        // 1.添加4个图像视图
        let count = 4
        let rect = UIScreen.main.bounds
        for i in 0 ..< count {
            
            // 设置图片视图
            let imageView = UIImageView(image: UIImage(named: "new_feature_\(i + 1)"))
            
            // 设置图片视图大小
            imageView.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            scrollView.addSubview(imageView)
        }
        
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.bounces = false
        scrollView.delegate = self
        
        // 隐藏按钮
        startButton.isHidden = true
        
        // 禁用pageControl交互
        pageControl.isUserInteractionEnabled = false
    }
    
}

extension SSWBNewFeatureView: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        // 1.一旦滚动,就隐藏按钮
        startButton.isHidden = true
        
        // 2.计算当前的偏移量
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        // 3.设置分页控件
        pageControl.currentPage = page
        
        // 4.分页控件隐藏
        pageControl.isHidden = (page == scrollView.subviews.count)
        
    }
    
    
    /// 减速了
    ///
    /// - Parameter scrollView: scrollView
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        // 滚动到最后一屏,让视图删除
        
        // 拿到页面的数量
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        if page == scrollView.subviews.count {
            removeFromSuperview()
        }
        
        // 如果是倒数第二页,显示按钮
        if page == scrollView.subviews.count - 1 {
            startButton.isHidden = false
        } else {
            startButton.isHidden = true
        }
    }
}
